package cn.stronglink.assetmanage;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.stronglink.assetmanage.business.check.view.CheckFragment;
import cn.stronglink.assetmanage.business.inspection.view.PatrolDetail.PatrolDetailFragment;
import cn.stronglink.assetmanage.business.inspection.view.PatrolFragment;
import cn.stronglink.assetmanage.business.inspection.view.assetDetail.PatrolAssetDetailFragment;
import cn.stronglink.assetmanage.business.inspection.view.repairDetail.RepairDetailFragment;
import cn.stronglink.assetmanage.business.inspection.view.resiger.RepairRegisterFragment;
import cn.stronglink.assetmanage.business.inventory.view.InventoryFragment;
import cn.stronglink.assetmanage.business.inventory.view.detail.InventoryDetailFragment;
import cn.stronglink.assetmanage.business.search.view.SearchFragment;
import cn.stronglink.assetmanage.business.setting.ipset.SystemFragment;
import cn.stronglink.assetmanage.business.sync.OneKeySyncFragment;
import cn.stronglink.assetmanage.business.task.view.TaskFragment;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.index.entity.PromissionEntity;
import cn.stronglink.assetmanage.index.entity.TaskEntity;
import cn.stronglink.assetmanage.index.fragment.MenuFragment;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import cn.stronglink.assetmanage.widget.SimpleToolbar;
import cn.stronglink.netrequest.business.user.LoginService;
import cn.stronglink.netrequest.util.HttpURL;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    public final static int FRAGMENT_CUSTOM_ID = -1;
    public final static int FRAGMENT_INVENTORY_DETAIL_ID = 99;
    public final static int FRAGMENT_PATROL_DETAIL_ID = 98;
    public final static int FRAGMENT_REPAIR_REGITER_ID = 97;
    public final static int FRAGMENT_REPAIR_DETAIL_ID = 96;
    public final static int FRAGMENT_PATROL_ASSET_DETAIL_ID = 95;

    private static String userName;
    List<TaskEntity> list = new ArrayList<>();
    @BindView(R.id.tvLoginName)
    TextView tvLoginName;
    @BindView(R.id.tvTitle)
    SimpleToolbar tvTitle;
    @BindView(R.id.frame_login_info)
    View fmView;
    FragmentManager fragmentManager = getSupportFragmentManager();
    LoginService service;
    Dialog mDialog;
    private Unbinder unbinder;
    private MenuFragment menuFragment;
    private Fragment currentFragment = new Fragment();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        unbinder = ButterKnife.bind(this);
        userName = User.getInstance().getName();
        if (userName != null) {
            tvLoginName.setText(userName);
        }
        addLeftPromission();
        initView();
        service = new LoginService();
        mDialog = CustomProgressDialog.createLoadingDialog(this, "同步中...");
        mDialog.setCancelable(false);

        tvTitle.setLeftTitleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                fragmentManager.popBackStack();
            }
        });
        checkSyncType();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
            EventBus.getDefault().post(list);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (currentFragment instanceof KeyEvent.Callback) {
            return ((KeyEvent.Callback) currentFragment).onKeyDown(keyCode, event);
        }
        return keyCode != KeyEvent.KEYCODE_BACK && super.onKeyDown(keyCode, event);
    }

    private void addLeftPromission() {
        TaskEntity entity = new TaskEntity();
        entity.setTaskPromission(1);
        entity.setTaskResuorces(R.drawable.task_press);
        entity.setTaskText("我的任务");
        list.add(entity);

        TaskEntity entity2 = new TaskEntity();
        entity2.setTaskPromission(2);
        entity2.setTaskResuorces(R.drawable.checkincoming_press);
        entity2.setTaskText("验收入库");
        list.add(entity2);

        TaskEntity entity3 = new TaskEntity();
        entity3.setTaskPromission(3);
        entity3.setTaskResuorces(R.drawable.inventory);
        entity3.setTaskText("盘点管理");
        list.add(entity3);

        TaskEntity entity4 = new TaskEntity();
        entity4.setTaskPromission(4);
        entity4.setTaskResuorces(R.drawable.inspection_press);
        entity4.setTaskText("巡检维修");
        list.add(entity4);

        TaskEntity entity5 = new TaskEntity();
        entity5.setTaskPromission(5);
        entity5.setTaskResuorces(R.drawable.onekeysync);
        entity5.setTaskText("一键同步");
        list.add(entity5);

        TaskEntity entity6 = new TaskEntity();
        entity6.setTaskPromission(6);
        entity6.setTaskResuorces(R.drawable.jserach);
        entity6.setTaskText("检索查找");
        list.add(entity6);

        TaskEntity entity7 = new TaskEntity();
        entity7.setTaskPromission(7);
        entity7.setTaskResuorces(R.drawable.systing);
        entity7.setTaskText("系统设置");
        list.add(entity7);
    }

    private void initView() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (null == menuFragment) {
            menuFragment = MenuFragment.getInstance();
            transaction.add(R.id.frame_recycle, menuFragment);
        }
        transaction.add(R.id.frame_business, new TaskFragment());
        transaction.commit();
    }

    private void checkSyncType() {
        int total = DaoManager.getDaoSession(MainActivity.this).getSyncTypesDao().queryBuilder().build().list().size();
        if (total == 0) {
            SyncTypes types1 = new SyncTypes();
            types1.setImgCheck(R.drawable.checked);
            types1.setImgUnCheck(R.drawable.uncheck);
            types1.setIsSelected(false);
            types1.setSyscTs(1);
            types1.setSysText("自动同步");
            long tp1 = DaoManager.getDaoSession(MainActivity.this).getSyncTypesDao().insert(types1);

            SyncTypes types2 = new SyncTypes();
            types2.setImgCheck(R.drawable.checked);
            types2.setImgUnCheck(R.drawable.uncheck);
            types2.setIsSelected(true);
            types2.setSyscTs(2);
            types2.setSysText("离线同步");
            long ty2 = DaoManager.getDaoSession(MainActivity.this).getSyncTypesDao().insert(types2);
        }
    }

    @OnClick(R.id.frame_login_info)
    public void loginOut() {
        AlertDialog.Builder ab = new AlertDialog.Builder(this);
        ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
                try {
                    service.loginOut(new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                            startActivity(intent);
                            finish();
                        }

                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    });
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        });
        ab.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        });
        ab.setMessage("确定要退出登录吗?");
        ab.setTitle("提示");
        ab.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventRegister(PromissionEntity position) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        Constants.isGetCheckData = false;
        Constants.isGetPatrolData = false;
        Constants.isGetRepairData = false;
        switch (position.getPosition()) {
            case FRAGMENT_CUSTOM_ID:
                if (position.getTitle() != null && !position.getTitle().isEmpty()) {
                    tvTitle.setMainTitle(position.getTitle());
                } else {
                    tvTitle.setMainTitle("自定义");
                }
                if (position.getFragment() != null) {
                    currentFragment = position.getFragment();
                }
                break;
            case 0:
                tvTitle.setMainTitle("我的任务");
                currentFragment = new TaskFragment();
                //showFragment(new TaskFragment());
                break;
            case 1:
                tvTitle.setMainTitle("验收收库");
                currentFragment = new CheckFragment();
                break;
            case 2:
                tvTitle.setMainTitle("盘点管理");
                currentFragment = new InventoryFragment();
                break;
            case 3:
                tvTitle.setMainTitle("巡检维修");
                currentFragment = new PatrolFragment();
                break;
            case 4:
                tvTitle.setMainTitle("一键同步");
                currentFragment = new OneKeySyncFragment();
                break;
            case 5:
                tvTitle.setMainTitle("检索查找");
                currentFragment = new SearchFragment();
                break;
            case 6:
                tvTitle.setMainTitle("系统设置");
                currentFragment = SystemFragment.getInstance();
                //showFragment(SystemFragment.getInstance());
                break;
            case FRAGMENT_INVENTORY_DETAIL_ID:
                tvTitle.setMainTitle("盘点详情");
                currentFragment = new InventoryDetailFragment();
                //showFragment(SystemFragment.getInstance());
                break;
            case FRAGMENT_PATROL_DETAIL_ID:
                tvTitle.setMainTitle("巡检详情");
                currentFragment = new PatrolDetailFragment();
                break;
            case FRAGMENT_REPAIR_REGITER_ID:
                tvTitle.setMainTitle("维修登记");
                currentFragment = new RepairRegisterFragment();
                break;
            case FRAGMENT_REPAIR_DETAIL_ID:
                tvTitle.setMainTitle("维修登记详情");
                currentFragment = new RepairDetailFragment();
                break;
            case FRAGMENT_PATROL_ASSET_DETAIL_ID:
                tvTitle.setMainTitle("巡检资产详情");
                currentFragment = new PatrolAssetDetailFragment();
                break;
            default:
                break;
        }

        if (currentFragment != null) {
            if (position.getBundle() != null) {
                currentFragment.setArguments(position.getBundle());
            }

            transaction.replace(R.id.frame_business, currentFragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        if (currentFragment instanceof KeyEvent.Callback) {
            return ((KeyEvent.Callback) currentFragment).onKeyLongPress(keyCode, event);
        }
        return super.onKeyLongPress(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (currentFragment instanceof KeyEvent.Callback) {
            return ((KeyEvent.Callback) currentFragment).onKeyLongPress(keyCode, event);
        }
        return keyCode != KeyEvent.KEYCODE_BACK && super.onKeyLongPress(keyCode, event);
    }

    @Override
    public boolean onKeyMultiple(int keyCode, int keyCode1, KeyEvent event) {
        if (currentFragment instanceof KeyEvent.Callback) {
            return ((KeyEvent.Callback) currentFragment).onKeyMultiple(keyCode, keyCode1, event);
        }
        return super.onKeyMultiple(keyCode, keyCode1, event);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mDialog != null) {
            mDialog.cancel();
        }
    }

    private Fragment getCurrentFragment() {
        FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment != null && fragment.isVisible()) {
                return fragment;
            }
        }
        return null;
    }
}
